﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TPCN.DAL;
using TPCN.Common;
using TPCN.Commons;

namespace TPCN.Admincp
{
    public partial class Dondathang : System.Web.UI.Page
    {
        private static string DonDatHangID = String.Empty;
        private static string ChitietdondathangID = String.Empty;
        private static bool inDetail = false;
        private static List<DonDatHangObj> source;
        private static List<ChiTietDonDatHangObj> listhang;
        private static DonDatHangObj obj;
        private static ChiTietDonDatHangObj detail;

        private const string UPDATE = "Cập nhật";
        private const string INSERT = "Thêm";
        private const string CMD_EDIT = "cmdEdit";
        private const string CMD_DELETE = "cmdDelete";
        private const string CMD_DETAIL = "cmdViewDetail";
        private const string ICON_PATH = "~/App_Themes/Admincp/Images/warning.png";
        private const string OK_ICON_PATH = "~/App_Themes/Admincp/Images/ok.png";

        private static bool isConfirm = false;
        private static bool isDelivering = false;
        private static bool isDelivered = false;
        private static bool isPaid = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridView();
                InitForm();
                OrderDetailPanel.Visible = false;
            }
        }

        private void InitForm()
        {
            OrderEditFormPanel.Visible = false;
            GridViewPanel.Visible = true;
            ButtonPanel.Visible = true;
            OrderDetailPanel.Visible = false;
            OrderDetailEditPanel.Visible = false;

            SetcboNhanhangValue();
            SetcboThanhtoanValue();
            LoadcboProduct();
            inDetail = false;
        }

        private void BindGridView()
        {
            source = new List<DonDatHangObj>();
            source = DonDatHangDAL.GetByAll();
            OrderGridView.DataSource = source;
            OrderGridView.DataBind();
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            if (inDetail)
            {
                OrderDetailPanel.Visible = false;
                OrderDetailEditPanel.Visible = true;
                ButtonPanel.Visible = false;
                btnSave_Detail.Text = INSERT;
            }
            else
            {
                TurnPanelOnOff();
                btnSave.Text = INSERT;
            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (inDetail)
            {
                for (int i = 0; i < ChitietdondathangGridView.Rows.Count; i++)
                {
                    GridViewRow row = ChitietdondathangGridView.Rows[i];
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                        if (chk.Checked)
                        {
                            string ID = row.Cells[1].Text;
                            ChiTietDonDatHangDAL.Delete(ID);
                        }
                    }
                }
                ChitietdondathangGridView.PageIndex = 0;
                OrderDetailBindGridView();
            }
            else
            {
                for (int i = 0; i < OrderGridView.Rows.Count; i++)
                {
                    GridViewRow row = OrderGridView.Rows[i];
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                        if (chk.Checked)
                        {
                            string ID = row.Cells[1].Text;
                            DonDatHangDAL.Delete(ID);
                            ChiTietDonDatHangDAL.DeleteByOrderID(ID);
                            DonHangTrangThaiDonHangDAL.DeleteByOrderID(ID);
                        }
                    }
                }
                OrderGridView.PageIndex = 0;
                BindGridView();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (inDetail)
                {
                    SetValueFromDetailForm();
                    switch (btnSave_Detail.Text)
                    {
                        case UPDATE:
                            ChiTietDonDatHangDAL.Update(detail);
                            OrderDetailBindGridView();
                            break;
                        case INSERT:
                            ChiTietDonDatHangDAL.Insert(detail);
                            OrderDetailBindGridView();
                            break;
                    }
                    ControlHelper.ResetControl(OrderDetailEditPanel);
                    OrderDetailEditPanel.Visible = false;
                    OrderDetailPanel.Visible = true;
                    ButtonPanel.Visible = true;
                    OrderDetailBindGridView();
                    detail = null;
                }
                else
                {
                    SetValueFromForm();
                    switch (btnSave.Text)
                    {
                        case UPDATE:
                            DonDatHangDAL.Update(obj);
                            BindGridView();
                            break;
                        case INSERT:
                            DonDatHangDAL.Insert(obj);
                            BindGridView();
                            break;
                    }
                    ControlHelper.ResetControl(OrderEditFormPanel);
                    TurnPanelOnOff();
                    obj = null;
                    Page.Response.Redirect(Request.RawUrl, true);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (inDetail)
            {
                ControlHelper.ResetControl(OrderDetailEditPanel);
                OrderDetailEditPanel.Visible = false;
                OrderDetailPanel.Visible = true;
                ButtonPanel.Visible = true;
            }
            else
            {
                TurnPanelOnOff();
                ControlHelper.ResetControl(OrderEditFormPanel);
                Page.Response.Redirect(Request.RawUrl, true);
            }

        }

        protected void OrderGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            OrderGridView.PageIndex = e.NewPageIndex;
            BindGridView();
        }

        protected void OrderGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            DonDatHangID = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case CMD_EDIT:
                    obj = new DonDatHangObj();
                    obj = DonDatHangDAL.GetByID(DonDatHangID);
                    FillValueToForm(obj);
                    btnSave.Text = UPDATE;
                    TurnPanelOnOff();
                    break;
                case CMD_DELETE:
                    DonDatHangDAL.Delete(DonDatHangID);
                    ChiTietDonDatHangDAL.DeleteByOrderID(DonDatHangID);
                    DonHangTrangThaiDonHangDAL.DeleteByOrderID(DonDatHangID);
                    BindGridView();
                    break;
                case CMD_DETAIL:
                    LoadOrderDetailInfo();
                    break;
            }
        }

        private void TurnPanelOnOff()
        {
            GridViewPanel.Visible = !GridViewPanel.Visible;
            OrderEditFormPanel.Visible = !OrderEditFormPanel.Visible;
            ButtonPanel.Visible = !ButtonPanel.Visible;
        }

        private void FillValueToForm(DonDatHangObj obj)
        {
            txtHotennguoinhan.Text = obj.Hotennguoinhan;
            txtSodienthoai.Text = obj.Sodienthoai;
            txtAddress.Text = obj.Diachinhanhang;
            txtComment.Text = obj.Ghichu;
            cboThanhtoan.SelectedValue = obj.PhuongthucthanhtoanID;
            cboNhanhang.SelectedValue = obj.Hinhthucnhanhang;
            txtAddress.Enabled = obj.Hinhthucnhanhang == "1";
            chkActive.Checked = Boolean.Parse(obj.Active);
        }

        protected void SetValueFromForm()
        {
            if (obj == null)
                obj = new DonDatHangObj();
            obj.Hotennguoinhan = txtHotennguoinhan.Text;
            obj.Sodienthoai = txtSodienthoai.Text;
            obj.Diachinhanhang = txtAddress.Text;
            obj.Ghichu = txtComment.Text;
            obj.Hinhthucnhanhang = cboNhanhang.SelectedValue;
            obj.Active = Convert.ToString(chkActive.Checked);
            obj.PhuongthucthanhtoanID = cboThanhtoan.SelectedValue;
            obj.Ngaylap = (String.IsNullOrEmpty(obj.Ngaylap) ? DateTime.Now.ToShortDateString() : obj.Ngaylap);
            obj.KhachID = String.IsNullOrEmpty(obj.KhachID) ? String.Empty : obj.KhachID;
        }

        protected string DisplayDeliver(Object o, Object add)
        {
            string type = Convert.ToString(o);
            string addr = Convert.ToString(add);
            if (type == Const.KEY_DELIVER_DEN_LAY_TRUC_TIEP)
                return "Đến lấy trực tiếp";
            else
                return addr;
        }

        protected string DisplayPayment(string id)
        {
            string str = String.Empty;
            switch (id)
            {
                case Const.KEY_PAYMENT_MONEY:
                    str = "Thanh toán tiền mặt";
                    break;
                case Const.KEY_PAYMENT_ATM:
                    str = "Chuyển khoản ngân hàng";
                    break;
                case Const.KEY_PAYMENT_OTHER:
                    str = "Khác";
                    break;
            }
            return str;
        }

        protected void cboNhanhang_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtAddress.Enabled = (cboNhanhang.SelectedValue == "1");
        }

        protected string FormatDatetime(Object o)
        {
            DateTime time = Convert.ToDateTime(o);
            return time.ToString("dd/MM/yyyy");
        }

        protected string GetProductNameFromID(Object id)
        {
            string mID = Convert.ToString(id);
            return HangDAL.GetNameByID(mID);
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            ChitietdondathangGridView.DataSource = null;
            OrderDetailPanel.Visible = false;
            GridViewPanel.Visible = true;
            BindGridView();
            inDetail = false;
        }

        protected void SetcboNhanhangValue()
        {
            cboNhanhang.Items.Add(new ListItem("Đến lấy hàng trực tiếp", Const.KEY_DELIVER_DEN_LAY_TRUC_TIEP));
            cboNhanhang.Items.Add(new ListItem("Giao hàng tại nhà", Const.KEY_DELIVER_GIAO_HANG_TAI_NHA));
        }

        protected void SetcboThanhtoanValue()
        {
            cboThanhtoan.Items.Add(new ListItem("Thanh toán bằng tiền mặt", Const.KEY_PAYMENT_MONEY));
            cboThanhtoan.Items.Add(new ListItem("Chuyển khoản ngân hàng", Const.KEY_PAYMENT_ATM));
            cboThanhtoan.Items.Add(new ListItem("Khác", Const.KEY_PAYMENT_OTHER));
        }

        /**
         * Order Detail
         **/

        protected void OrderDetailBindGridView()
        {
            listhang = ChiTietDonDatHangDAL.GetByOrderID(DonDatHangID);
            ChitietdondathangGridView.DataSource = listhang;
            ChitietdondathangGridView.DataBind();
        }

        protected void ChitietdondathangGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            ChitietdondathangID = e.CommandArgument.ToString();
            detail = new ChiTietDonDatHangObj();
            detail = ChiTietDonDatHangDAL.GetByID(ChitietdondathangID);
            switch (e.CommandName)
            {
                case CMD_EDIT:
                    FillValueToDetailForm(detail);
                    btnSave_Detail.Text = UPDATE;
                    OrderDetailEditPanel.Visible = true;
                    OrderDetailPanel.Visible = false;
                    ButtonPanel.Visible = false;
                    break;
                case CMD_DELETE:
                    ChiTietDonDatHangDAL.Delete(ChitietdondathangID);
                    OrderDetailBindGridView();
                    break;
            }
        }

        protected void ChitietdondathangGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ChitietdondathangGridView.PageIndex = e.NewPageIndex;
            OrderDetailBindGridView();
        }

        private void FillValueToDetailForm(ChiTietDonDatHangObj tmp)
        {
            cboProduct.SelectedValue = tmp.HangID;
            txtSoluong.Text = tmp.Soluong;
            txtProductComment.Text = tmp.Ghichu;
        }

        protected void SetValueFromDetailForm()
        {
            if (detail == null)
                detail = new ChiTietDonDatHangObj();
            detail.HangID = cboProduct.SelectedValue;
            detail.Soluong = txtSoluong.Text;
            detail.Ghichu = txtProductComment.Text;
            detail.DondathangID = DonDatHangID;
        }

        protected void LoadcboProduct()
        {
            List<HangObj> products = new List<HangObj>();
            products = HangDAL.GetByAll();
            cboProduct.DataSource = products;
            cboProduct.DataTextField = "Tenhang";
            cboProduct.DataValueField = "HangID";
            cboProduct.DataBind();
        }

        protected string BuildIconPath(Object ID)
        {
            string orderID = Convert.ToString(ID);
            isConfirm = false;
            isDelivering = false;
            isDelivered = false;
            isPaid = false;
            List<DonHangTrangThaiDonHangObj> l = new List<DonHangTrangThaiDonHangObj>();
            l = DonHangTrangThaiDonHangDAL.GetByOrder(orderID);
            for (int i = 0; i < l.Count; i++)
            {
                if (i > 1)
                    break;
                if (l[i].TrangthaiID == Const.KEY_STATUS_CONFIRMED)
                    isConfirm = true;
                else if (l[i].TrangthaiID == Const.KEY_STATUS_DELIVERING)
                    isDelivering = true;
                else if (l[i].TrangthaiID == Const.KEY_STATUS_DELIVERED)
                    isDelivered = true;
                else if (l[i].TrangthaiID == Const.KEY_STATUS_PAID)
                    isPaid = true;
            }
            if (isConfirm || isDelivered || isDelivering || isPaid)
                return OK_ICON_PATH;
            else
                return ICON_PATH;
        }

        protected void GetOrderStatus(string orderID)
        {
            isConfirm = false;
            isDelivering = false;
            isDelivered = false;
            isPaid = false;
            List<DonHangTrangThaiDonHangObj> l = new List<DonHangTrangThaiDonHangObj>();
            l = DonHangTrangThaiDonHangDAL.GetByOrder(orderID);
            for (int i = 0; i < l.Count; i++)
            {
                if (l[i].TrangthaiID == Const.KEY_STATUS_CONFIRMED)
                    isConfirm = true;
                else if (l[i].TrangthaiID == Const.KEY_STATUS_DELIVERING)
                    isDelivering = true;
                else if (l[i].TrangthaiID == Const.KEY_STATUS_DELIVERED)
                    isDelivered = true;
                else if (l[i].TrangthaiID == Const.KEY_STATUS_PAID)
                    isPaid = true;
            }
        }

        protected void LoadOrderDetailInfo()
        {
            obj = new DonDatHangObj();
            obj = DonDatHangDAL.GetByID(DonDatHangID);
            inDetail = true;
            lblNguoinhan.Text = obj.Hotennguoinhan;
            lblSodienthoai.Text = obj.Sodienthoai;
            lblNhanhang.Text = DisplayDeliver(obj.Hinhthucnhanhang, obj.Diachinhanhang);
            lblThanhtoan.Text = DisplayPayment(obj.PhuongthucthanhtoanID);
            OrderDetailPanel.Visible = true;
            GridViewPanel.Visible = false;
            OrderDetailBindGridView();
            GetOrderStatus(DonDatHangID);
            chkConfirmed.Checked = isConfirm;
            chkDelivering.Checked = isDelivering;
            chkDelivered.Checked = isDelivered;
            chkPaid.Checked = isPaid;
        }

        protected void UpdateOrderStatus(string OrderID, string StateID, bool lastState, bool currentStatus)
        {
            if (lastState != currentStatus)
            {
                if (currentStatus)
                {
                    DonHangTrangThaiDonHangObj tmp = new DonHangTrangThaiDonHangObj();
                    tmp.DondathangID = OrderID;
                    tmp.TrangthaiID = StateID;
                    tmp.Ngaythaydoi = DateTime.Now.ToShortDateString();
                    tmp.NhanvienID = "1";
                    DonHangTrangThaiDonHangDAL.Insert(tmp);
                }
                else
                {
                    DonHangTrangThaiDonHangDAL.DeleteByOrderAndState(OrderID, StateID);
                }
            }
        }

        protected void btnUpdateStatus_Click(object sender, EventArgs e)
        {
            UpdateOrderStatus(DonDatHangID, Const.KEY_STATUS_CONFIRMED, isConfirm, chkConfirmed.Checked);
            UpdateOrderStatus(DonDatHangID, Const.KEY_STATUS_DELIVERING, isDelivering, chkDelivering.Checked);
            UpdateOrderStatus(DonDatHangID, Const.KEY_STATUS_DELIVERED, isDelivered, chkDelivered.Checked);
            UpdateOrderStatus(DonDatHangID, Const.KEY_STATUS_PAID, isPaid, chkPaid.Checked);
            GetOrderStatus(DonDatHangID);
            chkConfirmed.Checked = isConfirm;
            chkDelivering.Checked = isDelivering;
            chkDelivered.Checked = isDelivered;
            chkPaid.Checked = isPaid;
        }
    }
}